package com.leon.alishop.core.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leon.alishop.core.service.GoodsSkuService;
import com.leon.alishop.dao.GoodsSkuDao;
import com.leon.alishop.model.GoodsSku;

@Service("goodsSkuService")
public class GoodsSkuServiceImpl implements GoodsSkuService{

	@Override
	public int insertOrUpdateSkuListForCrawl(List<GoodsSku> skuList,Long goodsId) {
		if(null == skuList
				|| skuList.size()==0
				|| goodsId == null)
			return 0;
		List<GoodsSku> cSkuList = goodsSkuDao.selectByGoodsId(goodsId);
		GoodsSku skuTemp;
		for (GoodsSku sku : skuList) {
			if((skuTemp = continueSku(cSkuList, sku)) != null){
				sku.setGoodsId(goodsId);
				if(skuTemp.getProviderSkuStock()!=null 
						&& skuTemp.getProviderSkuStock().equals(sku.getProviderSkuStock())
						&& skuTemp.getProviderSkuPrice() != null 
						&& skuTemp.getProviderSkuPrice().equals(sku.getProviderSkuPrice()))
					continue;
				goodsSkuDao.updateByIdSelective(sku);
			}else{
				sku.setGoodsId(goodsId);
				goodsSkuDao.insertSelective(sku);
			}
		}
		return skuList.size();
	}
	
	private GoodsSku continueSku(List<GoodsSku> cSkuList,GoodsSku sku){
		if(cSkuList == null 
				|| cSkuList.size()==0
				|| sku == null)
			return null;
		for (GoodsSku goodsSku : cSkuList) {
			if(goodsSku.getGoodsId().equals(sku.getGoodsId())
					&& goodsSku.getSizeAttrValId().equals(sku.getSizeAttrValId())
					&& goodsSku.getColorAttrValId().equals(sku.getColorAttrValId())){
				sku.setId(goodsSku.getId());
				return goodsSku;
			}
		}
		return null;
	}
	
	
	@Autowired
	private GoodsSkuDao goodsSkuDao;

}
